#include "server.h"

Servidor::Servidor(ServerCfg* cfg, Socket* sock) {
	this->cfg = *cfg;
	this->sock = sock;
}

Servidor::~Servidor() {

}

void Servidor::run() {
	//Recursos compartidos
	//unsigned int actual_connections = 0;
	Mutex general_mutex;
	//....................
	Socket* new_socket;
	ClientConversation* cc = 0;
	sock->Listen(cfg.GetPort());
	while (1) {
		//Si hago shutdown desde el main, lanza excepcion y corto el while
		try {
			new_socket = sock->Accept();
		} catch (const AcceptingException& e) {
			break;
		}
		cc = new ClientConversation(new_socket, &general_mutex);
		cc->start();
		//Agrego a la lista de clientes conectados
		general_mutex.lock();
		clients.push_back(cc);
		general_mutex.unlock();

	}
	//Independientemente de si quedaban o no, si un cliente no termino, not finished
	for (unsigned int i = 0; i < clients.size(); i++) {
		//Paro los threads;
		clients.at(i)->join();

	}

}
